/**
 * 模板选择器组件
 * 提供模板选择和预览功能
 */

import React, { useState, useEffect, useMemo } from 'react'
import { 
  Modal, 
  Input, 
  Select, 
  Card, 
  Row, 
  Col, 
  Tag, 
  Button, 
  Empty, 
  Spin, 
  Tabs, 
  Space,
  Typography,
  Divider,
  Badge
} from 'antd'
import { 
  SearchOutlined, 
  FileTextOutlined, 
  TagOutlined,
  ClockCircleOutlined,
  EyeOutlined,
  PlusOutlined
} from '@ant-design/icons'
import { 
  DocumentTemplate, 
  TemplateCategory, 
  TemplateLabelType,
  TemplateFilters 
} from '../../../types/template'
import { templateService } from '../../../services/templates'
import { getTemplateCategoryInfo, getTemplateTypeInfo } from '../../../services/templates/builtInTemplates'

const { Search } = Input
const { Option } = Select
const { Text, Paragraph } = Typography
const { TabPane } = Tabs

interface TemplatePickerProps {
  visible: boolean
  onSelect: (template: DocumentTemplate) => void
  onCancel: () => void
  category?: TemplateCategory
  type?: TemplateLabelType
}

interface TemplateCardProps {
  template: DocumentTemplate
  onSelect: (template: DocumentTemplate) => void
  onPreview: (template: DocumentTemplate) => void
}

/**
 * 模板卡片组件
 */
const TemplateCard: React.FC<TemplateCardProps> = ({ template, onSelect, onPreview }) => {
  const categoryInfo = getTemplateCategoryInfo().find(c => c.category === template.category)
  const typeInfo = getTemplateTypeInfo().find(t => t.type === template.type)
  
  const handleSelect = () => {
    onSelect(template)
  }

  const handlePreview = (e: React.MouseEvent) => {
    e.stopPropagation()
    onPreview(template)
  }

  return (
    <Card
      hoverable
      className="template-card"
      style={{ height: '100%' }}
      actions={[
        <Button 
          type="link" 
          icon={<EyeOutlined />} 
          onClick={handlePreview}
        >
          预览
        </Button>,
        <Button 
          type="primary" 
          icon={<PlusOutlined />} 
          onClick={handleSelect}
        >
          使用模板
        </Button>
      ]}
    >
      <Card.Meta
        title={
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <span>{categoryInfo?.icon}</span>
            <span className="template-title">{template.name}</span>
            {template.isBuiltIn && (
              <Badge count="内置" style={{ backgroundColor: '#52c41a' }} />
            )}
          </div>
        }
        description={
          <div>
            <Paragraph 
              ellipsis={{ rows: 2, tooltip: template.description }}
              style={{ marginBottom: 8, minHeight: 44 }}
            >
              {template.description}
            </Paragraph>
            
            <div style={{ marginBottom: 8 }}>
              <Tag color={typeInfo?.color}>{typeInfo?.name}</Tag>
              <Tag color="blue">{categoryInfo?.name}</Tag>
              {template.metadata.difficulty && (
                <Tag color={
                  template.metadata.difficulty === 'easy' ? 'green' :
                  template.metadata.difficulty === 'medium' ? 'orange' : 'red'
                }>
                  {template.metadata.difficulty === 'easy' ? '简单' :
                   template.metadata.difficulty === 'medium' ? '中等' : '困难'}
                </Tag>
              )}
            </div>
            
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, color: '#666' }}>
              <span>
                <ClockCircleOutlined style={{ marginRight: 4 }} />
                使用 {template.usageCount} 次
              </span>
              {template.metadata.estimatedLength && (
                <span>约 {template.metadata.estimatedLength} 字</span>
              )}
            </div>
            
            {template.tags.length > 0 && (
              <div style={{ marginTop: 8 }}>
                <TagOutlined style={{ marginRight: 4, fontSize: 12, color: '#666' }} />
                {template.tags.slice(0, 3).map(tag => (
                  <Tag key={tag} size="small" style={{ fontSize: 10 }}>
                    {tag}
                  </Tag>
                ))}
                {template.tags.length > 3 && (
                  <Text type="secondary" style={{ fontSize: 10 }}>
                    +{template.tags.length - 3}
                  </Text>
                )}
              </div>
            )}
          </div>
        }
      />
    </Card>
  )
}

/**
 * 模板预览组件
 */
const TemplatePreview: React.FC<{ 
  template: DocumentTemplate | null
  visible: boolean
  onClose: () => void 
}> = ({ template, visible, onClose }) => {
  if (!template) return null

  const categoryInfo = getTemplateCategoryInfo().find(c => c.category === template.category)
  const typeInfo = getTemplateTypeInfo().find(t => t.type === template.type)

  return (
    <Modal
      title={
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span>{categoryInfo?.icon}</span>
          <span>模板预览：{template.name}</span>
        </div>
      }
      visible={visible}
      onCancel={onClose}
      footer={[
        <Button key="close" onClick={onClose}>
          关闭
        </Button>
      ]}
      width={800}
      style={{ top: 20 }}
    >
      <div style={{ marginBottom: 16 }}>
        <Space>
          <Tag color={typeInfo?.color}>{typeInfo?.name}</Tag>
          <Tag color="blue">{categoryInfo?.name}</Tag>
          {template.metadata.difficulty && (
            <Tag color={
              template.metadata.difficulty === 'easy' ? 'green' :
              template.metadata.difficulty === 'medium' ? 'orange' : 'red'
            }>
              {template.metadata.difficulty === 'easy' ? '简单' :
               template.metadata.difficulty === 'medium' ? '中等' : '困难'}
            </Tag>
          )}
          {template.isBuiltIn && (
            <Badge count="内置模板" style={{ backgroundColor: '#52c41a' }} />
          )}
        </Space>
      </div>
      
      {template.description && (
        <div style={{ marginBottom: 16 }}>
          <Text strong>描述：</Text>
          <Paragraph>{template.description}</Paragraph>
        </div>
      )}
      
      <div style={{ marginBottom: 16 }}>
        <Text strong>模板内容：</Text>
        <div 
          style={{ 
            marginTop: 8,
            padding: 16, 
            backgroundColor: '#f5f5f5', 
            borderRadius: 6,
            maxHeight: 400,
            overflow: 'auto',
            fontFamily: 'monospace',
            fontSize: 13,
            lineHeight: 1.6,
            whiteSpace: 'pre-wrap'
          }}
        >
          {template.content}
        </div>
      </div>
      
      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, color: '#666' }}>
        <span>使用次数：{template.usageCount}</span>
        <span>预估长度：{template.metadata.estimatedLength || '未知'} 字</span>
        <span>创建时间：{template.createdAt.toLocaleDateString()}</span>
      </div>
    </Modal>
  )
}

/**
 * 模板选择器主组件
 */
export const TemplatePicker: React.FC<TemplatePickerProps> = ({
  visible,
  onSelect,
  onCancel,
  category,
  type
}) => {
  const [loading, setLoading] = useState(false)
  const [templates, setTemplates] = useState<DocumentTemplate[]>([])
  const [searchQuery, setSearchQuery] = useState('')
  const [selectedCategory, setSelectedCategory] = useState<TemplateCategory | undefined>(category)
  const [selectedType, setSelectedType] = useState<TemplateLabelType | undefined>(type)
  const [previewTemplate, setPreviewTemplate] = useState<DocumentTemplate | null>(null)
  const [previewVisible, setPreviewVisible] = useState(false)
  const [activeTab, setActiveTab] = useState('all')

  const categoryInfos = useMemo(() => getTemplateCategoryInfo(), [])
  const typeInfos = useMemo(() => getTemplateTypeInfo(), [])

  // 加载模板
  const loadTemplates = async () => {
    setLoading(true)
    try {
      const filters: TemplateFilters = {}
      
      if (selectedCategory) {
        filters.category = [selectedCategory]
      }
      
      if (selectedType) {
        filters.type = [selectedType]
      }

      const result = await templateService.searchTemplates(searchQuery, filters)
      
      if (result.success) {
        setTemplates(result.data.templates)
      } else {
        console.error('[模板选择器] 加载模板失败:', result.error)
        setTemplates([])
      }
    } catch (error) {
      console.error('[模板选择器] 加载模板异常:', error)
      setTemplates([])
    } finally {
      setLoading(false)
    }
  }

  // 初始化和数据变化时重新加载
  useEffect(() => {
    if (visible) {
      loadTemplates()
    }
  }, [visible, searchQuery, selectedCategory, selectedType])

  // 过滤模板
  const filteredTemplates = useMemo(() => {
    if (activeTab === 'all') {
      return templates
    } else if (activeTab === 'builtin') {
      return templates.filter(t => t.isBuiltIn)
    } else if (activeTab === 'custom') {
      return templates.filter(t => !t.isBuiltIn)
    }
    return templates
  }, [templates, activeTab])

  // 处理模板选择
  const handleTemplateSelect = (template: DocumentTemplate) => {
    onSelect(template)
  }

  // 处理模板预览
  const handleTemplatePreview = (template: DocumentTemplate) => {
    setPreviewTemplate(template)
    setPreviewVisible(true)
  }

  // 处理搜索
  const handleSearch = (value: string) => {
    setSearchQuery(value)
  }

  // 重置筛选
  const handleReset = () => {
    setSearchQuery('')
    setSelectedCategory(undefined)
    setSelectedType(undefined)
    setActiveTab('all')
  }

  return (
    <>
      <Modal
        title="选择模板"
        visible={visible}
        onCancel={onCancel}
        footer={null}
        width={1200}
        style={{ top: 20 }}
        destroyOnClose
      >
        <div style={{ marginBottom: 16 }}>
          <Row gutter={[16, 16]}>
            <Col span={8}>
              <Search
                placeholder="搜索模板名称、描述或标签"
                allowClear
                onSearch={handleSearch}
                onChange={(e) => setSearchQuery(e.target.value)}
                value={searchQuery}
              />
            </Col>
            <Col span={6}>
              <Select
                placeholder="选择分类"
                allowClear
                style={{ width: '100%' }}
                value={selectedCategory}
                onChange={setSelectedCategory}
              >
                {categoryInfos.map(info => (
                  <Option key={info.category} value={info.category}>
                    <span style={{ marginRight: 8 }}>{info.icon}</span>
                    {info.name} ({info.count})
                  </Option>
                ))}
              </Select>
            </Col>
            <Col span={6}>
              <Select
                placeholder="选择类型"
                allowClear
                style={{ width: '100%' }}
                value={selectedType}
                onChange={setSelectedType}
              >
                {typeInfos.map(info => (
                  <Option key={info.type} value={info.type}>
                    <Tag color={info.color} style={{ margin: 0 }}>
                      {info.name}
                    </Tag>
                    <span style={{ marginLeft: 8 }}>({info.count})</span>
                  </Option>
                ))}
              </Select>
            </Col>
            <Col span={4}>
              <Button onClick={handleReset} style={{ width: '100%' }}>
                重置筛选
              </Button>
            </Col>
          </Row>
        </div>

        <Tabs activeKey={activeTab} onChange={setActiveTab} style={{ marginBottom: 16 }}>
          <TabPane tab={`全部 (${templates.length})`} key="all" />
          <TabPane 
            tab={`内置模板 (${templates.filter(t => t.isBuiltIn).length})`} 
            key="builtin" 
          />
          <TabPane 
            tab={`自定义模板 (${templates.filter(t => !t.isBuiltIn).length})`} 
            key="custom" 
          />
        </Tabs>

        <div style={{ minHeight: 400, maxHeight: 600, overflow: 'auto' }}>
          <Spin spinning={loading}>
            {filteredTemplates.length > 0 ? (
              <Row gutter={[16, 16]}>
                {filteredTemplates.map(template => (
                  <Col key={template.id} xs={24} sm={12} lg={8}>
                    <TemplateCard
                      template={template}
                      onSelect={handleTemplateSelect}
                      onPreview={handleTemplatePreview}
                    />
                  </Col>
                ))}
              </Row>
            ) : (
              <Empty
                description={
                  searchQuery || selectedCategory || selectedType
                    ? "没有找到符合条件的模板"
                    : "暂无模板"
                }
              />
            )}
          </Spin>
        </div>
      </Modal>

      <TemplatePreview
        template={previewTemplate}
        visible={previewVisible}
        onClose={() => setPreviewVisible(false)}
      />
    </>
  )
}